package com.zrz.controller;

import com.zrz.XmlUtils.CheckUtil;
import com.zrz.XmlUtils.MessageUtil;
import com.zrz.XmlUtils.XmlUtil;
import com.zrz.domain.ImageUpload;
import com.zrz.model.auto.ImageMediaid;
import com.zrz.model.auto.User;
import com.zrz.service.UserService;
import com.zrz.service.WechatService;
import com.zrz.util.ImageUtil;
import com.zrz.util.LogUtils;
import com.zrz.util.UploadImageUitl;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet(urlPatterns = "/wechat/in")
public class WechatServlet extends HttpServlet {
    @Autowired
    WechatService wechatService;
    @Autowired
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LogUtils.info("servlet开始===doget");
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        try {
            PrintWriter out = resp.getWriter();
            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
                System.out.print(echostr);
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LogUtils.info("servlet开始===dopost");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        String message = "";
        try {
            Map<String, String> map = XmlUtil.xmlToMap(req);
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String eventType = map.get("Event");
            if (MessageUtil.MESSAGE_UNSUBSCIBE.equals(eventType)) {
                return;
            }
            if (MessageUtil.MESSAGE_SUBSCIBE.equals(eventType)) {
                if (map.containsKey("EventKey")) {
                    String param = null;
                    String eventKey = map.get("EventKey");
                    if (eventKey.contains("qrscene_")) {
                        param = eventKey.replace("qrscene_", "");
                    }
                    LogUtils.info("开始保存用户信息");
                    LogUtils.info("fromUserName:" + fromUserName + "===param:" + param);
                    wechatService.getSaveUserInfo(fromUserName, param);

                }
                message = "\u2728欢迎关注萃央红酒！\n" + "\u2728加入会员，月月免费领红酒~\n" + "\u2728点击“会员权益”-“加入会员”\n" + "\u2728充值299元成为会员\n" + "\u2728推广他人成功加入\n" + "\u2728还可获专属推广红酒一瓶！\n" + "\u2728山东华典集团运营，不会跑路\n"+ "\u2728咨询电话15508666911\n"+"\u2728更多详情点击： https://wechat.uwetech.cn/aboutOur";
                resp.getWriter().write(MessageUtil.textMsg(toUserName, fromUserName, message));
            }

            if (MessageUtil.EVENT_TYPE_CLICK.equalsIgnoreCase(eventType)) {
                String eventKey = map.get("EventKey");
                if (eventKey.equalsIgnoreCase("shoppingMall")) {
                    message = "敬请期待";
//                    ImageMediaid imageMediaid = wechatService.getMedidByName("xiaochengx.jpg");
//                    if (imageMediaid != null) {
//                        resp.getWriter().write(MessageUtil.imageMsg(fromUserName, toUserName, imageMediaid.getMediaid()));
//                    } else {
                        resp.getWriter().write(MessageUtil.textMsg(toUserName, fromUserName, message));
//                    }

                }
                if(eventKey.equalsIgnoreCase("extension")){
                    //生成组合图片
                    User user=userService.getUserInfoByOpenId(null,fromUserName);
                    if(user!=null){
                        String url=ImageUtil.addImage(user.getId());
                        ImageUpload imageUpload=userService.imageUpload(url);
                        if(imageUpload!=null){
                            resp.getWriter().write(MessageUtil.imageMsg(fromUserName, toUserName, imageUpload.getMedia_id()));
                        }
                    }
                }
            }
            if (msgType.equalsIgnoreCase(MessageUtil.MESSAGE_TEXT)) {
//                message = "\u2728欢迎关注萃央红酒！\n" + "\u2728加入会员，月月免费领红酒~\n" + "\u2728点击“会员权益”-“加入会员”\n" + "\u2728充值360元成为会员\n" + "\u2728即可抢占价值1888元礼包!\n" + "\u2728推广他人成功加入\n" + "\u2728还可获专属推广红酒一瓶！";
                ImageMediaid imageMediaid = wechatService.getMedidByName("guanzhu.jpg");
                if (imageMediaid != null&&map.get("Content").equals("推广")) {
                    resp.getWriter().write(MessageUtil.imageMsg(fromUserName, toUserName, imageMediaid.getMediaid()));
                }
//                else {
//                    resp.getWriter().write(MessageUtil.textMsg(toUserName, fromUserName, message));
//                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {

            if (out != null) {
                out.close();
            }
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init();
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    }

    private String emoji(int hexEmoji) {
        return String.valueOf(Character.toChars(hexEmoji));
    }
}
